package com.dhecp.project.storage.service.impl;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.core.utils.ReflectUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.business.domain.ProductActive;
import com.dhecp.project.common.domain.*;
import com.dhecp.project.common.service.UpdateLogService;
import com.dhecp.project.common.service.impl.BaseModuleServiceImpl;
import com.dhecp.project.purchase.domain.Payment;
import com.dhecp.project.purchase.domain.PurchaseOrder;
import com.dhecp.project.purchase.domain.PurchasePlan;
import com.dhecp.project.storage.domain.*;
import com.dhecp.project.storage.mapper.StockControlMapper;
import com.dhecp.project.storage.mapper.SubInvTransferMapper;
import com.dhecp.project.storage.service.SubInvTransferService;
import com.dhecp.project.system.service.SysDictionaryForFieldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: kjecp
 * @description: 储存 移仓单
 * @author: hlf
 * @create: 2022-09-08 19:22
 */
@Service
public class SubInvTransferServiceImpl extends BaseModuleServiceImpl implements SubInvTransferService {


    @Autowired
    private SubInvTransferMapper storageMapper;
    @Autowired
    private StockControlMapper stockControlMapper;
    @Autowired
    private UpdateLogService updateLogService;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    /**
     * @Description: 查询前一单NID、BID
     * @Param: [params] nid 必要参数：当前 单据编码
     * @return: com.dhecp.common.core.domain.AjaxResult  (data.nid 前一单NID， data.bid 前一单BID)
     * @Author: hlf
     * @date: 2022-05-09 10:08
     */
    @Override
    public AjaxResult queryLastNid(Map<String, Object> params) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (params.get("nid") == null || params.get("nid") == "") {
            params.put("nid", "0");
        }
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        ModuleNID moduleNID = storageMapper.selectLastNid(params);
        if (moduleNID == null) {
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfirstnid"), TypeUtils.mapToJson(dataMap).toString());
        }
        dataMap.put("nid", moduleNID.getNid().toString());
        dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
    }


    /**
     * @Description: 查询后一单NID、BID
     * @Param: [params] nid 必要参数：当前 单据编码
     * @return: com.dhecp.common.core.domain.AjaxResult  (data.nid 后一单NID， data.bid 后一单BID)
     * @Author: hlf
     * @date: 2022-05-09 10:09
     */
    @Override
    public AjaxResult queryNextNid(Map<String, Object> params) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (params.get("nid") == null || params.get("nid") == "" || "0".equals(params.get("nid").toString())) {
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        ModuleNID moduleNID = storageMapper.selectNextNid(params);
        if (moduleNID == null) {
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
        dataMap.put("nid", moduleNID.getNid().toString());
        dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
    }


    /**
     * @Description: 查询指定单nid的首记录
     * @Param: [params]
     * @return: com.dhecp.project.storage.domain.SubInvTransfer
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public SubInvTransfer queryFirstRecord(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return storageMapper.selectFirstRecordByNid(params);
    }

    /**
     * @Description: 查询指定单nid的整单录
     * @Param: [params] nid 必要参数：当前 单据编码
     * @return: java.util.List<com.dhecp.project.storage.domain.SubInvTransfer>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public List<SubInvTransfer> queryListByNid(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return storageMapper.selectByNid(params);
    }


    /**
     * @Description: 查询
     * @Param: [params]
     * @return: java.util.List<com.dhecp.project.storage.domain.SubInvTransfer>
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public List<SubInvTransfer> queryList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));    //常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        PageUtils.startPageStronger();
        return storageMapper.select(params);
    }

    /**
     * @Description: 保存
     * @Param: [params] moduleTable 必要参数：功能唯一标识
     * @Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     * @Param: [params] infoItems 必要参数：对应实体类的json格式字符串
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @SuppressWarnings("unchecked")
    @Override
    public AjaxResult saveData(Map<String, Object> params) {
        params.put("businessEntity", new SubInvTransfer());

        AjaxResult ajaxResult = this.saveDataBase(params);
        if (!"0".equals(ajaxResult.get("code").toString())) {
            throw new RuntimeException(ajaxResult.get("msg").toString());
        }

        String resNid = "0";
        Map<String, Object> infoMap = (Map<String, Object>) ajaxResult.get("infoMap");
        List<SubInvTransfer> businessDataList = (List<SubInvTransfer>) ajaxResult.get("businessDataList");


        List<RecordCheck> guidMapList = storageMapper.findRecords(infoMap.get("nid").toString());
        Map<String, Object> guidMap = new HashMap<String, Object>();
        if (!guidMapList.isEmpty()&& guidMapList.size() > 0) {
            if (infoMap.get("newNid") != null && "1".equals(infoMap.get("newNid").toString())) { //单号重复验证
                throw new RuntimeException(MessageUtils.message("module.error.retry"));
            }
            for (RecordCheck recordCheck : guidMapList) {
                if (recordCheck != null && recordCheck.getGuid() != null) {
                    guidMap.put(recordCheck.getGuid().toString(), "1");
                }
            }
        }

        if (businessDataList == null || businessDataList.size() == 0) {
            resNid = "0";
        } else {
            resNid = infoMap.get("nid").toString();
            for (SubInvTransfer businessData : businessDataList) {
                String guid = "";
                if (businessData.getGuid() == null) {
                    guid = RandomValueUtils.getGUID();
                    businessData.setGuid(guid);
                } else {
                    guid = businessData.getGuid().toString();
                	}
//                businessData.setGuid(guid);
                for (String field : infoMap.keySet()) { //遍历非网格字段，并赋值到实体中
                    Object fieldValue = infoMap.get(field);
                    ReflectUtils.setValue(businessData, field, fieldValue);
                }

                if (guidMap.get(guid) == null) {
                    businessData.setCreateTime(new Date());
                    storageMapper.insert(businessData);
                    updateLogService.addInsertLog(params.get("moduleTable").toString(), guid, "新增");
                } else {
                    SubInvTransfer oldData;
                    Map<String, Object> params2 = new HashMap<String, Object>();
                    params2.put("guid", guid);
                    oldData = storageMapper.findById(params2);

                    storageMapper.update(businessData);
                    updateLogService.addUpdateLog(params.get("moduleTable").toString(), guid, oldData, businessData, "修改");
                    guidMap.remove(guid);
                }
                

            }
        }

        if (!guidMap.isEmpty()) {
            for (String guid : guidMap.keySet()) {
                storageMapper.delete(guid);
            }
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), resNid);
    }

    /**
     * @Description: 删除
     * @Param: [params]
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult deleteData(Map<String, Object> params) {
        List<SubInvTransfer> businessDataList = JSON.parseArray(params.get("infoItems").toString(), SubInvTransfer.class);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (SubInvTransfer businessData : businessDataList) {
            storageMapper.delete(businessData);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }

    /**
     * @Description: 修改删除标志（预留）
     * @Param: [params] infoItems 必要参数：对应实体类的json格式字符串（仅需 guid 和 deleted）
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult updateDeleted(Map<String, Object> params) {
        List<UpdateDeleted> updateDeletedList = JSON.parseArray(params.get("infoItems").toString(), UpdateDeleted.class);
        if (updateDeletedList == null || updateDeletedList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (UpdateDeleted updateDeleted : updateDeletedList) {
            storageMapper.updateDeleted(updateDeleted);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }

    /**
     * @Description: 流转  —— 添加流程任务、修改流程状态及生效标志
     * @Param: [params] tableDataId 必要参数：单据编码（nid）
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult updateFlowGo(Map<String, Object> params) {
        Map<String, Object> infoMap = new HashMap<String, Object>();
        String nid = "0";
        if (params.get("tableDataId") == null || params.get("tableDataId") == "") {
            return AjaxResult.error(MessageUtils.message("module.error.lack", "单据编码【tableDataId】"));
        } else {
            nid = params.get("tableDataId").toString();
        }
        params.put("nid", nid);
        List<SubInvTransfer> businessDataList = storageMapper.selectByNid(params);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.nodata"));
        } else {
            infoMap.put("cid", businessDataList.get(0).getCid());
            infoMap.put("bUser", businessDataList.get(0).getbUser());
            infoMap.put("bDept", businessDataList.get(0).getbDept());
            infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
            infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
            infoMap.put("createTime", businessDataList.get(0).getCreateTime());
            params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
            params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
        }

        //流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
        if (params.get("optType") == null || params.get("optType") == "") {
            params.put("optType", "go");
        }
        UpdateFlow updateFlow = new UpdateFlow();
        updateFlow = this.FlowDealBase(params);

        for (SubInvTransfer businessData : businessDataList) {

//            if (updateFlow.getActiveFlow().equals("end")) {//当流程结束时
//                SubInvTransfer transfer = storageMapper.findByGuid(businessData.getGuid());
//                Map<String, Object> params2 = new HashMap<String, Object>();
//                params2.put("rkGuid",transfer.getRkGuid());
//                params2.put("vGsBm",transfer.getvGsBm());
//                params2.put("vHw",transfer.getGoodsAllocation());
//                params2.put("vKq",transfer.getGoodsArea());
//                params2.put("gDepot",transfer.getWarehouseAddress());
//                params2.put("productcode",transfer.getProductCode());
//                StockControl stockControl = stockControlMapper.findByMultiparameter(params2);
//
//                if(!transfer.getGoodsAllocation().equals(transfer.getToGoodsAllocation())){//不是同仓库
//
//                    if (stockControl!=null && stockControl.getProductNum()>0 && stockControl.getProductNum()>transfer.getAllotNum()){//当可用库存大于移仓库存时
//                        //进行移仓操作 产生新的库存信息
//                        GeneratedInventory(transfer,stockControl);//生成新的库存
//
//                    }else{//当可用库存小于于移仓库存时
//                        return AjaxResult.error("商品"+transfer.getProductName()+"可用库存不足!");
//                    }
//
//                }
//            }

            updateFlow.setGuid(businessData.getGuid().toString());
            storageMapper.updateFlow(updateFlow);
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }

    /**
     * @Description: 退回  —— 添加流程任务、修改流程状态及生效标志
     * @Param: [params] tableDataId 必要参数：单据编码（nid）
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult updateFlowBack(Map<String, Object> params) {
        Map<String, Object> infoMap = new HashMap<String, Object>();
        String nid = "0";
        if (params.get("tableDataId") == null || params.get("tableDataId") == "") {
            return AjaxResult.error(MessageUtils.message("module.error.lack", "单据编码【tableDataId】"));
        } else {
            nid = params.get("tableDataId").toString();
        }
        params.put("nid", nid);
        List<SubInvTransfer> businessDataList = storageMapper.selectByNid(params);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.nodata"));
        } else {
            infoMap.put("cid", businessDataList.get(0).getCid());
            infoMap.put("bUser", businessDataList.get(0).getbUser());
            infoMap.put("bDept", businessDataList.get(0).getbDept());
            infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
            infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
            infoMap.put("createTime", businessDataList.get(0).getCreateTime());
            params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
            params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
        }

        //流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
        if (params.get("optType") == null || params.get("optType") == "") {
            params.put("optType", "back");
        }
        UpdateFlow updateFlow = new UpdateFlow();
        updateFlow = this.FlowDealBase(params);

        for (SubInvTransfer businessData : businessDataList) {
//            if (businessDataList.get(0).getEffectStock() && !updateFlow.getEffectStock()){
//                //单流程重置时
//                SubInvTransfer transfer = storageMapper.findByGuid(businessData.getGuid());//获取当前数据
//                Map<String, Object> params2 = new HashMap<String, Object>();
//                params2.put("rkGuid",transfer.getRkGuid());
//                params2.put("vGsBm",transfer.getvGsBm());
//                params2.put("vHw",transfer.getGoodsAllocation());
//                params2.put("vKq",transfer.getGoodsArea());
//                params2.put("gDepot",transfer.getWarehouseAddress());
//                params2.put("productcode",transfer.getProductCode());
//                StockControl stockControl = stockControlMapper.findByMultiparameter(params2);//获取库存信息
//
//                if(!transfer.getGoodsAllocation().equals(transfer.getToGoodsAllocation())){//不是同仓库
//
//                    if (stockControl!=null && stockControl.getProductNum()>0 && stockControl.getProductNum()>transfer.getAllotNum()){//当可用库存大于移仓库存时
//
//                        //还原旧的库存信息
//                        ReturnInventory(transfer,stockControl);
//
//                    }else{//当可用库存小于于移仓库存时
//                        return AjaxResult.error("商品"+transfer.getProductName()+"可用库存不足!");
//                    }
//
//                }
//            }
            updateFlow.setGuid(businessData.getGuid().toString());
            storageMapper.updateFlow(updateFlow);
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }

    //移仓库存处理
    public void GeneratedInventory(SubInvTransfer subInvTransfer,StockControl oldStock) {//移仓,旧库存信息
        StockControl newStock = new StockControl();//生成新的库存数据
        //判断是否存在库存数据
        Map<String, Object> params2 = new HashMap<String, Object>();
        params2.put("rkGuid",oldStock.getRkGuid());
        params2.put("vGsBm",oldStock.getvGsBm());
        params2.put("vHw",subInvTransfer.getToGoodsAllocation());
        params2.put("vKq",subInvTransfer.getToGoodsArea());
        params2.put("gDepot",subInvTransfer.getToWarehouseAddress());
        params2.put("productcode",subInvTransfer.getProductCode());
        newStock = stockControlMapper.findByMultiparameter(params2);
        try {
            if (newStock != null){
                newStock.setProductNum(newStock.getProductNum()+subInvTransfer.getAllotNum());
                newStock.setProductNumAll(newStock.getProductNumAll()+subInvTransfer.getAllotNum());
                newStock.setPurchaseTotalPriceAll(oldStock.getPurchasePrice()*newStock.getProductNumAll());//采购总价
                newStock.setTotalAllotPrice(oldStock.getAllotPrice()*newStock.getProductNumAll());//调拨总价
                stockControlMapper.update(newStock);

                //进行移仓操作 还原库存数据
            }else{
                newStock = new StockControl();
                newStock.setGuid(RandomValueUtils.getGUID());
                newStock.setProductNum(subInvTransfer.getAllotNum());//可用数量
                newStock.setProductNumAll(subInvTransfer.getAllotNum());//库存总数
                newStock.setRkGuid(oldStock.getRkGuid());//入库标识
                newStock.setRkBid(oldStock.getRkBid());//入库单号
                newStock.setIsParent(oldStock.getIsParent());//是否母件
                newStock.setvHw(subInvTransfer.getToGoodsAllocation());//入库货位
                newStock.setvKq(subInvTransfer.getToGoodsArea());//库区
                newStock.setgDepot(subInvTransfer.getToWarehouseAddress());//所在仓库
                newStock.setvGsBm(oldStock.getvGsBm());//公司编码
                newStock.setvGsJc(oldStock.getvGsJc());//公司简称
                newStock.setvGsMc(oldStock.getvGsMc());//公司名称
                newStock.setProductCode(subInvTransfer.getProductCode());//商品编码
                newStock.setProductName(subInvTransfer.getProductName());;//商品名称
                newStock.setPurchasePrice(oldStock.getPurchasePrice());//商品采购价
                newStock.setPurchaseTotalPriceAll(oldStock.getPurchasePrice()*subInvTransfer.getAllotNum());//采购总价
                newStock.setAllotPrice(oldStock.getAllotPrice());//调拨单价
                newStock.setTotalAllotPrice(oldStock.getAllotPrice()*subInvTransfer.getAllotNum());//调拨总价
                newStock.setsDays(oldStock.getsDays());//库存天数
                newStock.setAssembleID(oldStock.getAssembleID());//组装单
                newStock.setPurchaseStorageID(oldStock.getPurchaseStorageID());//采购入库单
                newStock.setPurchaseOrderID(oldStock.getPurchaseOrderID());//采购订单
                newStock.setPurchasePlanID(oldStock.getPurchasePlanID());//采购计划单
                newStock.setdRkSj(oldStock.getdRkSj());//入库日期
                newStock.setCreateTime(new Date());//创建日期
                stockControlMapper.insert(newStock);
            }
            oldStock.setProductNum(oldStock.getProductNum()-subInvTransfer.getAllotNum());
            oldStock.setProductNumAll(oldStock.getProductNumAll()-subInvTransfer.getAllotNum());
            stockControlMapper.update(oldStock);


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //还原库存
    public void ReturnInventory(SubInvTransfer subInvTransfer,StockControl oldStock) {//移仓,旧库存信息
        StockControl newStock = new StockControl();//生成新的库存数据
        //判断是否存在库存数据
        Map<String, Object> params2 = new HashMap<String, Object>();
        params2.put("rkGuid",oldStock.getRkGuid());
        params2.put("vGsBm",oldStock.getvGsBm());
        params2.put("vHw",subInvTransfer.getToGoodsAllocation());
        params2.put("vKq",subInvTransfer.getToGoodsArea());
        params2.put("gDepot",subInvTransfer.getToWarehouseAddress());
        params2.put("productcode",subInvTransfer.getProductCode());
        newStock = stockControlMapper.findByMultiparameter(params2);
        try {
            if (newStock != null){//还原库存
                newStock.setProductNum(newStock.getProductNum()-subInvTransfer.getAllotNum());
                newStock.setProductNumAll(newStock.getProductNumAll()-subInvTransfer.getAllotNum());
                newStock.setPurchaseTotalPriceAll(oldStock.getPurchasePrice()*newStock.getProductNumAll());//采购总价
                newStock.setTotalAllotPrice(oldStock.getAllotPrice()*newStock.getProductNumAll());//调拨总价
                stockControlMapper.update(newStock);

                oldStock.setProductNum(oldStock.getProductNum()+subInvTransfer.getAllotNum());
                oldStock.setProductNumAll(oldStock.getProductNumAll()+subInvTransfer.getAllotNum());
                //修改旧的库存信息
                stockControlMapper.update(oldStock);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
